<?php
class brand extends core {
	public function __construct() {
		parent::__construct();
	}

	//index
	public function index() {
		$where = '';
		$brand_id = (isset($_GET['brand_id']) && trim($_GET['brand_id'])) ? intval($_GET['brand_id']) : '';
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
		if ($keyword) {
			$where .= "AND (name LIKE '%{$keyword}%')";
		}
		if ($brand_id) {
			$where .= "AND b.id='{$brand_id}'";
		}
		//分页
		$this->setpages(array( 'brand_id'=>$brand_id, 'keyword'=>$keyword));

		$sql = "SELECT * FROM jf_brand WHERE 1 {$where} ORDER BY sort ASC";
		$rs = $this->ezr->get_results($sql);
		$nav = $this->ezr->get_navigation();
		$this->smarty->assign('rs',$rs);

		$this->smarty->assign('page',$nav);
		$this->display();
	}

	//add
	public function add() {
		if (IS_POST) { //添加
			$this->save();
		} else { //显示
			$this->display();
		}
	}

	//edit
	public function edit() {
		if (IS_POST) { //添加
			$this->save();
		} else { //显示	
			$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
			$sql = "SELECT * FROM jf_brand b  WHERE id='{$id}'";
			$row = $this->db->get_row($sql);
			$this->smarty->assign('row', $row);
			$this->display();
		}
	}
	
	//写入到数据库
	public function save() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : '';
		$memo = (isset($_POST['memo']) && trim($_POST['memo'])) ? trim($_POST['memo']) : '';
		$keywords = (isset($_POST['keywords']) && trim($_POST['keywords'])) ? trim($_POST['keywords']) : '';
		$sort = (isset($_POST['sort']) && intval($_POST['sort'])) ? intval($_POST['sort']) : 999;
		$status = (isset($_POST['status']) && intval($_POST['status'])) ? intval($_POST['status']) : 0;
		//图片
		$pic = upload_one_file('brand', 'pic');
		//sql
		if ($id > 0) {  //edit
			$sql = "UPDATE jf_brand SET name='{$name}', memo='{$memo}', keywords='{$keywords}', sort='{$sort}', status='{$status}'  
				WHERE id='{$id}'";
			$this->db->query($sql);
			if($pic){
				$sql = "UPDATE jf_brand SET pic = '{$pic}' WHERE id='{$id}' ";
				$this->db->query($sql);
			}
		} else { //add
			$sql = "INSERT INTO jf_brand(name, memo, keywords, sort, status,pic) 
				VALUES('{$name}', '{$memo}', '{$keywords}', '{$sort}', '{$status}', '{$pic}')";
			$this->db->query($sql);
			$id = $this->db->insert_id;
		}
		//exit;
		header("Location:?app=brand");
	}

	//delete
	public function delete() {
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "DELETE FROM jf_brand WHERE id='{$id}'";
		$this->db->query($sql);
		//exit;
		header("Location:?app=brand");
	}
}
